import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;


import java.io.IOException;
import java.util.Date;

/**
 * Created by xiang.yu on 2017/7/10.
 */
public class NewAcctIdBuilder {
    public static void main(String[] args) {
        String urlCreate = "https://api.netease.im/nimserver/user/create.action";
        String urlUpdate = "https://api.netease.im/nimserver/user/update.action";
        p("h111",urlCreate);
    }

    public static String p(String phone,String url){
        String token=null;
        String appKey = "162d05aab5ec45e76833174a06b6429e";
        String appSecrt = "3feba7dc5679";
        String num = "123456";
        String time = String.valueOf(new Date().getTime() / 1000);
        String str = CheckSumBuilder.getCheckSum(appSecrt, num, time);
        System.out.println(str);

        PostMethod postMethod = new PostMethod("https://api.netease.im/nimserver/user/create.action");
        // 填入各个表单域的值
        NameValuePair[] data = {
                new NameValuePair("accid", phone)};
        // 将表单的值放入postMethod中
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        postMethod.setRequestBody(data);
        postMethod.setRequestHeader("AppKey", appKey);
        postMethod.setRequestHeader("Nonce", num);
        postMethod.setRequestHeader("CurTime", time);
        postMethod.setRequestHeader("CheckSum", str);
        // 执行postMethod
        int statusCode = 0;
        try {
            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            statusCode = httpClient.executeMethod(postMethod);
            String result = postMethod.getResponseBodyAsString();
            JSONObject jsonResponse = JSONObject.fromObject(result);

            if(jsonResponse.getJSONObject("code").equals("414")&&"Already Register".equals(jsonResponse.getJSONObject("desc"))){
                token = p("h111","https://api.netease.im/nimserver/user/update.action");
            }else {
                token = jsonResponse.getJSONObject("info").getString("token");
            }

            System.out.println(statusCode);
            System.out.println(result);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }
}
